package cn.quevo.ucenter.core.entity;

import javax.servlet.http.HttpServletRequest;

import cn.quevo.core.lang.JSONUtils;
import cn.quevo.core.lang.StringUtils;
import cn.quevo.ucenter.core.OAuthContext;
import cn.quevo.ucenter.core.OAuthUtil;
import lombok.Getter;

@Getter
public class OauthRequest {

    /** 客户端ID */
    private String clientId;
    /** 客户端秘钥 */
    private String clientSecret;
    /** 重定向URL */
    private String redirectUri;
    /** 刷新Token */
    private String refreshToken;
    /** 授权Code */
    private String authCode;
    /** 授权类型 */
    private String grantType;
    /** 用户名 */
    private String userName;
    /** 密码 */
    private String password;
    /** 返回类型 */
    private String responseType;
    public OauthRequest(HttpServletRequest request) {
        this.init(request);
    }
    
    private void init(HttpServletRequest request) {
        this.redirectUri = request.getParameter(OAuthContext.OAUTH_REDIRECT_URI);
        this.grantType = request.getParameter(OAuthContext.OAUTH_GRANT_TYPE);
        this.authCode = request.getParameter(OAuthContext.OAUTH_CODE);
        this.refreshToken = request.getParameter(OAuthContext.OAUTH_REFRESH_TOKEN);
        this.userName = request.getParameter(OAuthContext.OAUTH_USERNAME);
        this.password = request.getParameter(OAuthContext.OAUTH_PASSWORD);
        this.responseType = request.getParameter(OAuthContext.OAUTH_RESPONSE_TYPE);
        this.clientId = request.getParameter(OAuthContext.OAUTH_CLIENT_ID);
        if(!StringUtils.isBlank(request.getHeader(OAuthContext.HeaderType.AUTHORIZATION))) {
            String[] auth = OAuthUtil.decodeClientAuthenticationHeader(request.getHeader(OAuthContext.HeaderType.AUTHORIZATION));
            if(auth != null && auth.length == 2) {
                this.clientId = auth[0].trim();
                this.clientSecret = auth[1].trim();
            }
        }
        System.out.println("JSON:"+JSONUtils.format(this));
    }
}
